<?php
	session_start();
	require ('host_config.php');
	if (!isset($_GET['action']))
		$action = $_POST['action'];
	else
		$action = $_GET["action"];
	
	switch ($action) {
		case "login":
			$account = $_POST["account"];
			$password = $_POST["password"];
			User_Controller::checkPwd($account, $password);
			break;
		case "logout":
			session_destroy();
			header("location:login.php");
			break;
		case "add_user":
			$account = $_POST['account'];
			$password = $_POST['password'];
			$pwdConform = $_POST['pwdConform'];
			$shopName = $_POST['shopName'];
			$secName = $_POST['secName'];
			$email = $_POST['email'];
			User_Controller::lenthError($account, 帳號);
			if ($password != $pwdConform)
				User_Controller::errorMsg('密碼不相同');
			else {
				User_Controller::lenthError($shopName, 店家名稱);
				User_Controller::lenthError($email, 電子信箱);
				if (preg_match('/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/', $email))
					User_Controller::add_user($account, $password, $shopName, $secName, $email);
				else
					User_Controller::errorMsg('Email格式有誤');
			}
			break;
		case "modShopInfo":
			if (isset($_SESSION['loginid']) && isset($_SESSION['shopid'])){
				require_once(Models_DIR.'page_model.php');
				$page_model = new Page_Model();
				$shopid = $_SESSION['shopid'];
				$loginid = $_SESSION['loginid'];
				//處理常用欄位
				$query_col_name = array("fullname", "address", "tel", "memo", "food1", "food2", "food3", "food4", "maxofnumber", "perordernumber");
				$form_value = array($_POST['restName'], $_POST['address'], $_POST['phone'], $_POST['content'], $_POST['food1_txt'], $_POST['food2_txt'], $_POST['food3_txt'], $_POST['food4_txt'], $_POST['maxNumber'], $_POST['singleNumber']);
				$shopInfo = $page_model->showModInfo($shopid);
				for ($i=0; $i<sizeof($form_value); $i++) {
					if ($shopInfo[$i] != $form_value[$i]) {
						if ($i == 0) {
							$form_value[$i] = MySQL::real($form_value[$i]);
							$sql = "UPDATE LoginUser SET shopname = '$form_value[$i]' WHERE loginid = '$loginid'";
							MySQL::query($sql);
						}
						$form_value[$i] = MySQL::real($form_value[$i]);
						$sql = "UPDATE Shops SET $query_col_name[$i] = '$form_value[$i]' WHERE shopid = '$shopid'";
						MySQL::query($sql);
					}
				}
				//處理圖片部分
				$count = 1;
				$pic = array("pic1", "pic2", "pic3", "pic4");
				for($i=0; $i<4; $i++) {
					if ($_FILES['file'.$i]['name'] != NULL) {
						$path = User_Controller::uploadPic($_FILES['file'.$i]);
						$sql = "UPDATE Shops SET $pic[$i] = '$path' WHERE shopid = '$shopid'";
						MySQL::query($sql);
					}
				}
				if ($_FILES['shopPhoto']['name'] != NULL){
					$path = User_Controller::uploadPic($_FILES['shopPhoto']);
					$sql = "UPDATE Shops SET pic5 = '$path' WHERE shopid = '$shopid'";
					MySQL::query($sql);
				}
			}else
				User_Controller::errorMsg('error!!');
			header("location:index.php");
			break;
		case "addShopInfo":
			if (isset($_SESSION['loginid']) && $_SESSION['shopid'] == 0) {
				require_once(Models_DIR.'page_model.php');
				$page_model = new Page_Model();
				$loginid = $_SESSION['loginid'];
				//處理文字欄位
				$form_value = array($_POST['restName'], $_POST['restSecName'], $_POST['address'], $_POST['phone'], $_POST['content'], $_POST['food1_txt'], $_POST['food2_txt'], $_POST['food3_txt'], $_POST['food4_txt'], $_POST['maxNumber'], $_POST['singleNumber']);
				$form_name = array('餐廳名稱', '餐廳分店名稱', '地址', '電話', '內容', '菜單一', '菜單二', '菜單三', '菜單4', '最大訂位人數', '單筆訂位人數');
				for ($i=0; $i<sizeof($form_value); $i++) 
					User_Controller::lenthError($form_value[$i], $form_name[$i]);
				$path = array(NULL, NULL, NULL, NULL, NULL);
				for ($i=0; $i<4; $i++) 
					$path[$i] = User_Controller::uploadPic($_FILES['file'.$i]);
				if ($_FILES['shopPhoto']['name'] == NULL)
					User_Controller::errorMsg('店家招牌需要上傳');
				else
					$path[4] = User_Controller::uploadPic($_FILES['shopPhoto']);
				$fullname = $form_value[0]."-".$form_value[1];
				$sql = "INSERT INTO Shops VALUES(NULL, '$fullname', '$form_value[2]', '$form_value[3]', '$form_value[4]', 3, '$form_value[5]', '$form_value[6]', '$form_value[7]', '$form_value[8]', '$path[0]', '$path[1]', '$path[2]', '$path[3]', '$path[4]', '$form_value[9]', '$form_value[10]', 0, 0)";
				MySQL::query($sql);
				$sql = "UPDATE LoginUser SET shopname = '$fullname' WHERE loginid = '$loginid'";
				MySQL::query($sql);
				$sql = "SELECT shopid FROM Shops WHERE fullname = '$fullname'";
				$row = MySQL::query_row($sql);
				$_SESSION['shopid'] = $row[0];
				header("location:index.php");
			}else
				User_Controller::errorMsg('error!!');
			break;
		//威丞需要的function start
		case "getClient":
			$shopid = $_SESSION['shopid'];
			$flag = $_GET['flag'];
			if (isset($shopid) && isset($flag)) {
				$shopid = htmlspecialchars($shopid);
				$flag = htmlspecialchars($flag);
				User_Controller::getClient($shopid, $flag);
			}else
				User_Controller::errorMsg('error!!');
			break;
		case "delClient":
			$shopid = $_SESSION['shopid'];
			$clientid = $_POST['clientid'];
			if (isset($shopid) && isset($clientid)) {
				$shopid = htmlspecialchars($shopid);
				$clientid = htmlspecialchars($clientid);
				User_Controller::delClient($shopid, $clientid);
			}else
				User_Controller::errorMsg('error!!');
			break;
		case "clientCheckIn":
			$shopid = $_SESSION['shopid'];
			$clientid = $_POST['clientid'];
			if (isset($shopid) && isset($clientid)) {
				$shopid = htmlspecialchars($shopid);
				$clientid = htmlspecialchars($clientid);
				User_Controller::clientCheckIn($shopid, $clientid);
			}else
				User_Controller::errorMsg('error!!');
			break;
		case "assignTable":
			$shopid = $_SESSION['shopid'];
			$clientid = $_POST['clientid'];
			$table = $_POST['table'];
			if (isset($shopid) && isset($clientid) && isset($table)) {
				$shopid = htmlspecialchars($shopid);
				$clientid = htmlspecialchars($clientid);
				$table = htmlspecialchars($table);
				User_Controller::assignTable($shopid, $clientid, $table);
			}else
				User_Controller::errorMsg('error!!');
			break;
		case "finishedEating":
			$shopid = $_SESSION['shopid'];
			$clientid = $_POST['clientid'];
			if (isset($shopid) && isset($clientid)) {
				$shopid = htmlspecialchars($shopid);
				$clientid = htmlspecialchars($clientid);
				User_Controller::finishedEating($shopid, $clientid);
			}else
				User_Controller::errorMsg('error!!');
			break;
		case "clientNotify":
			$shopid = $_SESSION['shopid'];
			$clientid = $_POST['clientid'];
			if (isset($shopid) && isset($clientid)) {
				$shopid = htmlspecialchars($shopid);
				$clientid = htmlspecialchars($clientid);
				User_Controller::clientNotify($shopid, $clientid);
			}else
				User_Controller::errorMsg('error!!');
			break;
		case "getShopState":
			$shopid = $_SESSION['shopid'];
			if (isset($shopid)) {
				$shopid = htmlspecialchars($shopid);
				User_Controller::getShopState($shopid);
			}else
				User_Controller::errorMsg('error!!');
			break;
		case "shopSwitch":
			$shopid = $_SESSION['shopid'];
			$switch = $_POST['switch'];
			if (isset($shopid) && isset($switch)) {
				$shopid = htmlspecialchars($shopid);
				$switch = htmlspecialchars($switch);
				User_Controller::shopSwitch($shopid, $switch);
			}else
				User_Controller::errorMsg('error!!');
			break;
	}

	class User_Controller {
		function checkPwd($account, $password) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->checkPwd($account, $password);
		}
		function add_user($account, $password, $shopName, $secName, $email) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->add_user($account, $password, $shopName, $secName, $email);
		}
		function uploadPic($file) {
			$upload_path = "uploads/";
		 	$possible = "_0123456789"."abcdefghijklmnopqrstuvwxyz"."ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		 	$temp = 0;
		 	$count = 0;
		    /*temp 用於計算檔案上傳的錯誤
		   	店面照片已有進行驗證
		   	如果照片未上傳擇$temp++
		    如果附檔名有誤$temp = 10
		    如果上傳檔案大小有誤$temp = 20
		    如上傳失敗$temp = 30
		    */
		    $max_size = 4*1024; //限制可檔案大小為4KB
		    $total_uploads = 5;
	    	$limitedext = array("bmp","gif","jpg","jpeg","png");//設定可上傳的檔案類型(副檔名)
	 		$str = ""; 
			while(strlen($str) < 3) {$str .= substr($possible, (rand() % strlen($possible)), 1);}
	        $uploadfilename=time().$str;
	        $file_name = $file['name'];
	        $file_tmp = $file['tmp_name'];
	        $File_Extension = explode(".", $file_name);
	        $File_Extension = $File_Extension[count($File_Extension)-1];
	        if($file_name == NULL)
				$path = "uploads/";
	        elseif($file['error'] > 0){
	            echo "上傳錯誤代碼:".$file['error'];
	            exit;
	        }
	        elseif(($max_size > 0) && ($file['size'] > $max_size)){
	            echo "您上傳的檔案大小大於".$max_size."位元組";
	            $temp = 20;
	        }
	        elseif(!in_array($File_Extension,$limitedext)){
	        	echo "$File_Extension <br /> $limitedext <br />";
	            echo "不支援此檔案類型<br />";
	            $temp = 10;
	        }
	        elseif(move_uploaded_file($file_tmp, $upload_path.$uploadfilename.".".$File_Extension)){
				$path = $upload_path.$uploadfilename.".".$File_Extension;
	        }
	        else{
				$temp = 30;
	        }
		    if ($temp == 10) {
		    	echo "<script language='javascript'>";
		    	echo "alert('副檔名有誤（只允許GIF和JPEG檔）');";
		    	echo "history.back();";
		    	echo "</script>";
		    	die();
		    }else if ($temp == 20) {
		    	echo "<script language='javascript'>";
		    	echo "alert('無法上傳，請檢查檔案是否小於400 KB');";
		    	echo "history.back();";
		    	echo "</script>";
		    	die();
		    }else if ($temp == 30) {
		    	echo "<script language='javascript'>";
		    	echo "alert('無法上傳');";
		    	echo "history.back();";
		    	echo "</script>";
		    	die();
		    }
	        return $path;
		}
		function getClient($shopid, $flag) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->getClient($shopid, $flag);
		}
		function delClient($shopid, $clientid) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->delClient($shopid, $clientid);
		}
		function clientCheckIn($shopid, $clientid) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->clientCheckIn($shopid, $clientid);
		}
		function assignTable($shopid, $clientid, $table) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->assignTable($shopid, $clientid, $table);
		}
		function finishedEating($shopid, $clientid) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->finishedEating($shopid, $clientid);
		}
		function clientNotify($shopid, $clientid) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->clientNotify($shopid, $clientid);
		}
		function getShopState($shopid) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->getShopState($shopid);
		}
		function shopSwitch($shopid, $switch) {
			require_once (Models_DIR.'user_model.php');
			$user_model = new User_Model();
			$user_model->shopSwitch($shopid, $switch);
		}
		function lenthError($str, $name) {
			if (strlen($str) == 0) {
				echo '<noscript>'.$name.'不得為空</noscript>';
				echo '<script language="javascript">';
				echo 'alert("'.$name.'不得為空");';
				echo 'history.back();';
				echo '</script>';
			}
		}
		function errorMsg($str) {
			echo '<noscript>'.$str.'</noscript>';
			echo '<script language="javascript">';
			echo 'alert("'.$str.'");';
			echo 'history.back();';
			echo '</script>';
		}
	}
?>